﻿using MahApps.Metro.Controls;
using Red.Controls.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;

namespace Red.Controls
{
    /// <summary>
    /// Interaction logic for CommandPalette.xaml
    /// </summary>
    public partial class CommandPalette : MetroWindow, INotifyPropertyChanged
    {
        #region Data

        private List<CommandPaletteItem> _items;
        private ICollectionView _itemsView;
        private string _searchText;

        /// <summary>
        /// Object to store additional data. It is passed in CommandPaletteEventArgs passed through Hiding event.
        /// </summary>
        private object _argument;

        #endregion Data

        #region Events

        public delegate void CommandPaletteHiding( CommandPalette sender, CommandPaletteEventArgs args );
        public event CommandPaletteHiding Hiding;

        private void OnHiding( bool result )
        {
            if ( Hiding != null )
                Hiding( this, new CommandPaletteEventArgs { Argument = _argument, Result = result } );
        }

        #endregion Events

        #region Properties

        public List<CommandPaletteItem> Items
        {
            get { return _items; }
            set
            {
                if ( _items != null && _items.SequenceEqual( value ) )
                    return;

                _items = value;
                _itemsView = CollectionViewSource.GetDefaultView( _items );
                _itemsView.Filter += o =>
                {
                    if ( _searchText == null )
                        return true;

                    var cmdPaletteItem = o as CommandPaletteItem;
                    return cmdPaletteItem.Name.ToLower().Contains( _searchText.ToLower() );
                };

                OnPropertyChanged();
            }
        }

        public CommandPaletteItem SelectedItem { get; set; }

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if ( _searchText == value )
                    return;

                _searchText = value;
                _itemsView.Refresh();
                _itemsListBox.SelectedIndex = 0;
            }
        }

        #endregion Properties

        #region Public Metodes

        public void ResetInitialState()
        {
            _searchTextBox.Text = null;
            _itemsListBox.SelectedIndex = 0;

            var item = _itemsListBox.ItemContainerGenerator.ContainerFromIndex( 0 ) as ListBoxItem;
            if ( item != null )
                item.Focus();

            _searchTextBox.Focus();
        }

        public void Show( object argument )
        {
            _argument = argument;
            Show();
        }

        #endregion Public Metodes

        #region C-tor

        public CommandPalette()
        {
            DataContext = this;
            InitializeComponent();
            _searchTextBox.Focus();
        }

        #endregion C-tor

        #region Private methods

        private void HideCommandPalette( bool success )
        {
            OnHiding( success );
            Hide();
        }

        #endregion Private methods

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged( [CallerMemberName] string propertyName = null )
        {
            if ( PropertyChanged != null )
                PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
        }

        #endregion INotifyPropertyChanged

        #region Event handlers

        private void CommandPalette_OnKeyDown( object sender, KeyEventArgs e )
        {
            if ( e.Key == Key.Enter )
            {
                SelectedItemClick();
                HideCommandPalette( true );
            }

            if ( e.Key == Key.Escape )
                HideCommandPalette( false );
        }

        private void ListBoxItem_Click( object sender, MouseButtonEventArgs e )
        {
            SelectedItemClick();
            HideCommandPalette( true );
        }

        private void SelectedItemClick()
        {
            // SelectedItem can be null if we have an empty command palette or when filtered view has no visible results.
            if ( SelectedItem != null )
                SelectedItem.RaiseClick();
        }

        private void CommandPalette_OnPreviewKeyDown( object sender, KeyEventArgs e )
        {
            if ( e.Key != Key.Down && e.Key != Key.Up && e.Key != Key.PageDown && e.Key != Key.PageUp )
            {
                _searchTextBox.Focus();
            }
            else
            {
                var item = _itemsListBox.ItemContainerGenerator.ContainerFromIndex( _itemsListBox.SelectedIndex ) as ListBoxItem;
                if ( item != null )
                    item.Focus();
            }
        }

        private void CommandPalette_OnDeactivated(object sender, EventArgs e)
        {
            HideCommandPalette( false );
        }

        #endregion Event handlers
    }

    public class CommandPaletteEventArgs : EventArgs
    {
        public object Argument { get; set; }
        public bool Result { get; set; }
    }
}
